package com.umeox.watch.audiobooks.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.audiobooks.R;
import com.umeox.watch.audiobooks.adapter.AudiobooksAdapter;
import com.umeox.watch.audiobooks.db.AllStory;
import com.umeox.watch.audiobooks.db.AllStoryDao;
import com.umeox.watch.audiobooks.db.AppDatabase;
import com.umeox.watch.audiobooks.event.PlayStateEvent;
import com.umeox.watch.audiobooks.utils.StoryManager;
import com.umeox.watch.audiobooks.utils.StoryManagerKt;
import com.umeox.watch.audiobooks.utils.ThreadPoolExecutorUtils;
import com.umeox.watch.moto.apiclient.model.StoryDTO;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;
import com.yc.music.model.AudioBean;
import com.yc.music.service.PlayService;
import com.yc.music.tool.BaseAppHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rambo 2024/5/20/0020
 * Describe:
 */
public class AllStoryActivity extends ThemeAppCompatActivity implements Runnable, AudiobooksAdapter.OnClickListener {

    private RecyclerView mStoryRv;
    private List<AudioBean> mStoriesList;
    private AudiobooksAdapter mAdapter;
    private AllStoryDao allStoryDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_all_story);
        EventBus.getDefault().register(this);
        allStoryDao = AppDatabase.Companion.get().allStoryDao();
        mStoriesList = new ArrayList<>();
        mStoriesList.clear();
        mStoryRv = findViewById(R.id.rv_stories);
        mAdapter = new AudiobooksAdapter(this, R.layout.item_aduio);
        mAdapter.setOnClickListener(this);
        mStoryRv.setAdapter(mAdapter);
        mStoryRv.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

        loadBbData();
        ThreadPoolExecutorUtils threadPoolExecutorUtils = new ThreadPoolExecutorUtils();
        threadPoolExecutorUtils.execute(this);

    }

    private void loadBbData() {
        // 先拿本地的数据展示
        List<AllStory> allStoryList = allStoryDao.loadAll();
        covert2AudioBeanList(allStoryList, true);
    }

    private void getAllStoryDataFromServer() {
        // 刷新服务器最新的数据替换本地并保存
        try {
            List<StoryDTO> storyDTOList = PushApiClientProxy.fetchBinder().getStoriesPage();
            if (storyDTOList != null && !storyDTOList.isEmpty()) {
                Logger.e(storyDTOList.toString());
                allStoryDao.deleteAll();
                List<AllStory> allStories = new ArrayList<>();
                for (StoryDTO storyDTO : storyDTOList) {
                    AllStory story = new AllStory();
                    story.setId(storyDTO.id);
                    story.setName(storyDTO.name);
                    story.setCoverUrl(storyDTO.coverUrl);
                    story.setAuthor(storyDTO.author);
                    story.setStoryUrl(storyDTO.storyUrl);
                    story.setStoryLength(storyDTO.storyLength);
                    allStories.add(story);
                }
                allStoryDao.save(allStories);
                covert2AudioBeanList(allStories, false);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        // For test
        /*try {
            String storiesJsonStr = UtilKt.getDataFromJson("stories_data.json");
            JSONArray jsonArray= new JSONArray(storiesJsonStr);
            Logger.e("jsonArray=" + jsonArray);

            List<StoryBean> storyBeanList = GsonUtils.toList(jsonArray.toString(), StoryBean.class);
            if (storyBeanList != null) {
                for (StoryBean storyBean : storyBeanList) {
                    AudioBook audioBook = new AudioBook();
                    audioBook.setId(storyBean.getId());
                    audioBook.setName_ar(storyBean.getName_ar());
                    audioBook.setName_en(storyBean.getName_en());
                    audioBook.setImage_src(storyBean.getImage_src());
                    audioBook.setFile_src(storyBean.getFile_src());
                    mStoriesList.add(audioBook);
                }
            }
            StoryManager.INSTANCE.getAllStoryList().clear();
            StoryManager.INSTANCE.getAllStoryList().addAll(mStoriesList);
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            Logger.e("size=" + mStoriesList.size());
            mAdapter.setStories(mStoriesList);
        }*/
    }

    private void covert2AudioBeanList(List<AllStory> allStoryList, boolean inMainUI) {
        if (allStoryList == null) {
            return;
        }
        mStoriesList.clear();
        for (AllStory story : allStoryList) {
            AudioBean audioBook = new AudioBean();
            audioBook.setId(String.valueOf(story.getId()));
            audioBook.setTitle(story.getName());
            audioBook.setArtist(story.getAuthor());
            audioBook.setCoverPath(story.getCoverUrl());
            audioBook.setPath(story.getStoryUrl());
            audioBook.setDuration(story.getStoryLength() * 1000L);
            mStoriesList.add(audioBook);
        }
        StoryManager.INSTANCE.getAllStoryList().clear();
        StoryManager.INSTANCE.getAllStoryList().addAll(mStoriesList);
        if (inMainUI) {
            mAdapter.setStories(mStoriesList);
            PlayService playService = BaseAppHelper.get().getMusicService();
            if (playService != null) {
                AudioBean playingAudio = playService.getPlayingMusic();
                if (playingAudio != null) {
                    mAdapter.setCurAudioId(playingAudio.getId());
                }
            }
        } else {
            runOnUiThread(() -> {
                mAdapter.setStories(mStoriesList);
                PlayService playService = BaseAppHelper.get().getMusicService();
                if (playService != null) {
                    AudioBean playingAudio = playService.getPlayingMusic();
                    if (playingAudio != null) {
                        mAdapter.setCurAudioId(playingAudio.getId());
                    }
                }
            });
        }

    }

    @Override
    public void onItemClick(AudioBean item) {
        String selectAudioId = item.getId();
        mAdapter.setCurAudioId(selectAudioId);
        mAdapter.notifyDataSetChanged();
        Intent intent = new Intent(this, PlayingActivity.class);
        intent.putExtra(StoryManagerKt.INTENT_KEY_LIST_TYPE, StoryManagerKt.LIST_TYPE_ALL);
        intent.putExtra(StoryManagerKt.INTENT_KEY_AUDIO_ID, selectAudioId);
        startActivity(intent);
    }

    @Override
    public void run() {
        getAllStoryDataFromServer();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPlayStateChange(PlayStateEvent event) {
        Logger.e("==============onPlayStateChange==================");
        if (mAdapter != null) {
            PlayService playService = BaseAppHelper.get().getMusicService();
            if (playService != null) {
                AudioBean playingAudio = playService.getPlayingMusic();
                if (playingAudio != null) {
                    mAdapter.setCurAudioId(playingAudio.getId());
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
